/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.daydream.template.sequence.context;

import com.google.common.base.MoreObjects;

import org.pajamas.daydream.template.sequence.SequenceContext;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParseException;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * @author william
 * @since 2024/4/5
 */
public class SpELContext implements SequenceContext {

    private final ExpressionParser parser;

    private final EvaluationContext context;

    public SpELContext(ExpressionParser parser, EvaluationContext context) {
        this.parser = MoreObjects.firstNonNull(parser, new SpelExpressionParser());
        this.context = context;
    }

    public SpELContext(EvaluationContext context) {
        this(null, context);
    }

    @Nullable
    @Override
    public Object doGetValue(@Nonnull String key) {
        try {
            Expression expression = this.parser.parseExpression(key);
            return expression.getValue(this.context);
        } catch (ParseException | EvaluationException ex) {
            return null;
        }
    }
}
